<!--
 * @Author: lihaogn
 * @Date: 2022-05-17 20:31:59
 * @LastEditTime: 2022-05-18 13:42:57
 * @LastEditor: lihaogn
 * @Description: 
 * @FilePath: \lix-vue2-demos\src\views\demo\apply\file-visit\index.vue
-->
<template>
  <div class="file-visit-page">
    <el-card>
      <div slot="header">通过 change 事件访问选择的文件</div>
      <div>
        <input type="file" id="input" @change="handleFile" />
        <pre>{{ fileInfoStr }}</pre>
      </div>
    </el-card>

    <el-card>
      <div slot="header">隐藏难看的 input 元素</div>
      <div>
        <input
          type="file"
          ref="fileElemRef"
          multiple
          accept="image/*"
          style="display:none"
          @change="handleFiles"
        />
        <el-button @click="selectFile">Select some files</el-button>
        <pre>{{ filesInfoStr }}</pre>
      </div>
    </el-card>

    <DragFile></DragFile>
    <FilePreview></FilePreview>
    <FileUpload></FileUpload>
  </div>
</template>

<script>
import DragFile from './modules/DragFile.vue'
import { unitTranform } from '@/utils/common'
import FilePreview from './modules/FilePreview.vue'
import FileUpload from './modules/FileUpload.vue'
export default {
  components: { DragFile, FilePreview, FileUpload },
  data() {
    return {
      fileInfoStr: '',
      filesInfoStr: ''
    }
  },
  methods: {
    /**
     * @author: lihaogn
     * @Date: 2022-05-17 15:42:30
     * @description: 选择按钮点击事件
     * @return {*}
     */
    selectFile() {
      this.$refs.fileElemRef.click()
    },
    /**
     * @author: lihaogn
     * @Date: 2022-05-17 15:42:07
     * @description: 处理多个文件的选择
     * @param e - 事件对象
     * @return {*}
     */
    handleFiles(e) {
      let files = e.target.files
      let str = ''
      for (let i = 0; i < files.length; i++) {
        str +=
          'name: ' +
          files[i].name +
          ', size: ' +
          unitTranform(files[i].size) +
          '\r\n'
      }
      this.filesInfoStr = str
    },
    /**
     * @author: lihaogn
     * @Date: 2022-05-17 15:41:39
     * @description: 处理单个文件的选择
     * @param {*} e - 事件对象
     * @return {*}
     */
    handleFile(e) {
      let file = e.target.files[0]
      this.fileInfoStr +=
        'name: ' + file.name + '\r\n' + 'size: ' + file.size + ' b'
    }
  }
}
</script>

<style lang="less" scoped>
.file-visit-page {
  display: flex;

  .el-card {
    margin: 0 10px 10px 0;
  }
}
</style>
